<template>
  <view class="container">
    <!--  token列表  -->
    <view class="card-layout ver-layout-center">
      <view class="card-title-layout hor-layout-center-all">
        <view class="card-title">token列表</view>
        <button class="add-btn" size="mini" type="primary" @click="addTokenProcess">新增</button>
      </view>
      <view v-if="tokenList.length" class="ver-layout token-list-layout top-list-layout">
        <view class="token-list-line hor-layout-center">
          <view v-for="(item,index) in tokenHeaderList" :key="index"
                class="token-item header-item hor-layout-center-all"
                :class="{'left-item':index==0,'token-action-item':!item.key}">
            {{ item.label }}
          </view>
        </view>
        <view v-for="(item,index) in tokenList" :key="index" class="token-list-line hor-layout-center">
          <view v-for="(hItem,hIndex) in tokenHeaderList" :key="hIndex" class="token-item hor-layout-center-all"
                :class="{'left-item':hIndex==0,'token-action-item':!item.key}">
            <view v-if="hItem.key" class="token-item-content single-line-text">{{ item[hItem.key] }}</view>
            <view v-else class="hor-layout-center">
              <button class="token-btn" size="mini" type="primary" @click="pushMessage(item)">推送消息</button>
              <button class="token-btn" size="mini" type="default" @click="updateToken(item)">修改</button>
              <button class="token-btn" size="mini" type="warn" @click="removeToken(item)">删除</button>
            </view>
          </view>
        </view>
      </view>
      <view v-else class="list-no-data">暂无数据</view>
    </view>

    <!--  消息列表  -->
    <view class="card-layout ver-layout-center">
      <view class="card-title-layout hor-layout-center-all">
        <view class="card-title">消息列表</view>
        <button class="add-btn" size="mini" @click="getMessageList">刷新</button>
      </view>
      <view v-if="hmsMessageList.length" class="ver-layout token-list-layout">
        <view class="token-list-line hor-layout-center">
          <view v-for="(item,index) in hmsMessageHeaderList" :key="index"
                class="token-item header-item hor-layout-center-all single-line-text"
                :class="{'left-item':index==0,'message-action-item':!item.key}">
            {{ item.label }}
          </view>
        </view>
        <view v-for="(item,index) in hmsMessageList" :key="index" class="token-list-line hor-layout-center">
          <view v-for="(hItem,hIndex) in hmsMessageHeaderList" :key="hIndex" class="token-item hor-layout-center-all"
                :class="{'left-item':hIndex==0,'message-action-item':!hItem.key}">
            <view v-if="hItem.key=='desc'" class="token-item-content single-line-text hor-layout-center">
              <uni-tag :text="item[hItem.key]" size="small" type="success"></uni-tag>
            </view>
            <view v-else-if="hItem.key" class="token-item-content single-line-text">
              {{ item[hItem.key] }}
            </view>
            <view v-else class="hor-layout-center">
              <button class="token-btn" size="mini" type="warn" @click="removeMessage(item)">删除</button>
            </view>
          </view>
        </view>
      </view>
      <view v-else class="list-no-data">暂无数据</view>
    </view>

    <!--  添加token  -->
    <view v-if="showAddTokenDialog" class="dialog-layout ver-layout-center-all" @click="showAddTokenDialog=false">
      <view class="add-token-layout ver-layout-center" @click.stop>
        <view class="add-token-title">{{ tokenDialogTitle }}</view>
        <view class="hor-layout-center label-item">
          <view class="label-view">设备信息：</view>
          <input class="input-view" placeholder="请输入desc" v-model="tokenObj.desc">
        </view>
        <view class="hor-layout-center label-item">
          <view class="label-view">token值：</view>
          <input class="input-view" placeholder="请输入token" v-model="tokenObj.token">
        </view>
        <button class="save-btn" size="mini" type="primary" @click="saveToken">保存</button>
      </view>
    </view>
  </view>
</template>

<script>
import UniTag from "../../../components/uni-tag/uni-tag";

export default {
  components: {UniTag},
  data() {
    return {
      tokenHeaderList: [
        {label: '设备信息', key: 'desc'},
        {label: 'token', key: 'token'},
        {label: '操作', key: ''},
      ],
      tokenList: [],
      tokenObj: {
        token: '',
        desc: '',
      },
      hmsMessageHeaderList: [
        {label: '目标设备', key: 'desc'},
        {label: '发送时间', key: 'sendTime'},
        {label: '回执时间', key: 'backTime'},
        {label: 'msg', key: 'msg'},
        {label: '操作', key: ''},
      ],
      hmsMessageList: [],
      showAddTokenDialog: false,
      hmsWebUrl: "https://developer.huawei.com/consumer/cn/service/josp/agc/index.html#/myProject/388421841222037640/9249519184595935885",
    }
  },
  computed: {
    tokenDialogTitle() {
      return this.tokenObj._id ? "修改token" : "添加token"
    }
  },
  async onLoad() {
    await this.getTokenList()
    await this.getMessageList()
  },
  methods: {
    async getTokenList() {
      let options = {action: 'getHmsTokenList'}
      let result = await this.requestCloud('com-power', options)
      console.log("getTokenList", result)
      this.tokenList = result.data
    },
    addTokenProcess() {
      this.showAddTokenDialog = true
    },
    async pushMessage(item) {
      let options = {action: 'sendHmsMsg', tokenArr: item.token, desc: item.desc}
      let result = await this.requestCloud('com-power', options, "推送")
      await this.getMessageList()
    },
    updateToken(item) {
      this.showAddTokenDialog = true
      this.tokenObj = item
    },
    async removeToken(item) {
      let options = {action: 'removeHmsToken', id: item._id}
      let result = await this.requestCloud('com-power', options, "删除")
      await this.getTokenList()
    },
    async saveToken() {
      if (!this.tokenObj.token || !this.tokenObj.desc) {
        this.showToast("请将信息填写完整！", false)
        return
      }
      if (this.tokenObj._id) {
        let options = {action: 'updateHmsToken', ...this.tokenObj, id: this.tokenObj._id}
        let res = await this.requestCloud('com-power', options, "修改")
      } else {
        let options = {action: 'addHmsToken', ...this.tokenObj}
        let res = await this.requestCloud('com-power', options, "新增")
      }
      this.showAddTokenDialog = false
      await this.getTokenList()
    },
    async getMessageList() {
      let options = {action: 'getHmsMessageList'}
      let result = await this.requestCloud('com-power', options)
      console.log("getTokenList", result)
      this.hmsMessageList = result.data.map(item => {
        item.sendTime = this.timestampToDate(item.sendTimeId)
        item.backTime = this.timestampToDate(item.backTimeId)
        return item
      })
    },
    timestampToDate(timestamp) {
      if (!timestamp) return ""
      let date = new Date(timestamp);
      let year = date.getFullYear();
      let month = date.getMonth() + 1; // 月份从0开始，需要加1
      let day = date.getDate();
      let hours = date.getHours();
      let minutes = date.getMinutes();
      let seconds = date.getSeconds();
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    async removeMessage(item) {
      let options = {action: 'removeHmsMessage', id: item._id}
      let result = await this.requestCloud('com-power', options, "删除")
      await this.getMessageList()
    },
    async requestCloud(name, data, theme = '') {
      return new Promise((resolve, reject) => {
        uni.showLoading({mask: true})
        uniCloud.callFunction({
          name, data,
          success: res => {
            uni.hideLoading()
            if (theme) this.showToast(`${theme}成功！`)
            setTimeout(() => resolve(res.result), 700)
          },
          fail: err => {
            uni.hideLoading()
            if (theme) this.showToast(`${theme}失败！`, false)
            setTimeout(() => resolve({}), 700)
          }
        })
      })
    },
    showToast(title, success = true) {
      uni.showToast({title: title, icon: success ? 'success' : 'error'})
    }
  }
}
</script>

<style lang="less" scoped>
.card-layout {
  margin: 10px;
  background: #d5dadc;
  width: calc(100% - 10 * 2px);
  border: 1px solid #eaeaea;
  overflow-x: scroll;

  .card-title-layout {
    position: relative;
    width: 100%;
    margin-top: 10px;

    .card-title {
      color: #325993;
      font-size: 19px;
      font-weight: bold;
    }

    .add-btn {
      position: absolute;
      right: 10%;
    }
  }

  .top-list-layout {
    height: 20vh !important;
  }

  .token-list-layout {
    width: calc(100% - 20 * 2px);
    margin: 20px;
    height: 45vh;
    overflow-y: scroll;

    .token-list-line {
      width: 100%;

      .token-item {
        flex: 1;
        flex-shrink: 0;
        overflow: hidden;
        height: 35px;
        user-select: text;
        border-bottom: 1px solid #817878;
        border-right: 1px solid #999999;

        .token-btn {
          margin-right: 10px;
        }

        .token-item-content {
          margin: 0px 6px;
        }
      }

      .message-action-item {
        width: 100px;
        flex: unset;
      }

      //.token-action-item {
      //  width: 300px;
      //}

      .left-item {
        border-left: 1px solid #999999;
      }

      .header-item {
        border-top: 1px solid #999999;
        font-weight: bold;
      }
    }
  }
}

.dialog-layout {
  position: fixed;
  top: 0px;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);

  .add-token-layout {
    width: calc(50% - 5 * 2%);
    height: fit-content;
    background: white;
    background: white;
    border-radius: 10px;
    padding: 20px;

    .add-token-title {
      font-size: 18px;
      font-weight: bold;
    }

    .label-item {
      margin-top: 10px;
      width: 100%;

      .label-view {
        width: 80px;
        color: #494949;
        flex-shrink: 0;
      }

      .input-view {
        width: 100%;
        padding: 5px 10px;
        margin-left: 10px;
        border-radius: 5px;
        border: 1px solid #999999;
      }
    }

    .save-btn {
      margin-top: 20px;
    }
  }
}

@media screen and (min-width: 100px) and (max-width: 575px) {
  .token-list-layout {
    width: 1000px !important;
  }
}
</style>
